<template>
  <page>
    <template v-slot:header>
      <h2>
        <i class="el-icon-tickets"></i>
        <span>{{ $t("log.log") }}</span>
      </h2>
    </template>
    <template v-slot:content>
      <el-card>
        <div slot="header" class="card-header">
          <span>{{ $t("log.log_detail") }}</span>
        </div>
        <div>
          <el-row>
            <el-col :span="4" class="ky-left"> {{ $t("name") }}: </el-col>
            <el-col :span="20" class="ky-right">
              {{ detailMessage.action || "-" }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="ky-left">
              {{ $t("system.status") }}:
            </el-col>
            <el-col :span="20" class="ky-right">
              {{ detailMessage.status || "-" }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="ky-left"> {{ $t("result") }}: </el-col>
            <el-col :span="20" class="ky-right">
              {{ detailMessage.result || "-" }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="ky-left"> {{ $t("log.module") }}: </el-col>
            <el-col :span="20" class="ky-right">
              {{ detailMessage.module || "-" }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="ky-left">
              {{ $t("system.batch_name") }}:
            </el-col>
            <el-col :span="20" class="ky-right">
              {{ detailMessage.batchName || "-" }}
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="ky-left">
              {{ $t("log.operator") }}:
            </el-col>
            <el-col :span="20" class="ky-right">
              {{ detailMessage.username || "-" }}
            </el-col>
          </el-row>
          <el-row v-if="detailMessage.module === '自定义脚本模块'">
            <el-col :span="4" class="ky-left">
              {{ $t("system.script_content") }}:
            </el-col>
            <el-col :span="20" class="ky-right">
              <p class="script_content">
                {{ detailMessage.kylinSubLogs[0].scriptContent }}
              </p>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="4" class="ky-left">
              {{ $t("log.task_process") }}:
            </el-col>
            <el-col :span="20" class="ky-right progress">
              <el-progress
                :color="getColor"
                :percentage="getProgress"
                :format="format()"
              ></el-progress>
            </el-col>
          </el-row>
        </div>
      </el-card>
      <search class="search" v-if="displaySystem">
        <div>
          <span class="label">{{ $t("system.ip_address") }}</span>
          <el-input
            style="width: 215px"
            v-model="search_criteria.ip"
            size="small"
            class="size"
          />
        </div>
        <div>
          <span class="label">{{ $t("system.system_version") }}</span>
          <el-select
            v-model="search_criteria.version"
            size="small"
            class="size"
          >
            <el-option
              v-for="item in versions"
              :key="item"
              :value="item"
              :label="item"
            >
            </el-option>
          </el-select>
        </div>
        <!-- <div>
          <span class="label">{{ $t("log.error_code") }}</span>
          <el-select v-model="search_criteria.code" size="small" class="size">
            <el-option
              v-for="item in codes"
              :key="item"
              :value="item"
              :label="item"
            >
            </el-option>
          </el-select>
        </div> -->
        <div>
          <el-button size="small" class="kylin-button" @click="handleSearch">{{
            $t("Search")
          }}</el-button>
          <el-button size="small" class="kylin-button" @click="handleReset">{{
            $t("Reset")
          }}</el-button>
        </div>
      </search>
      <el-drawer :visible.sync="drawer" :with-header="false">
        <el-card>
          <div slot="header" class="card-header">
            <span>{{ $t("log.log_detail") }}</span>
          </div>
          <div class="drawer">
            <p>{{ detail }}</p>
          </div>
        </el-card>
      </el-drawer>
      <el-dialog
        :title="title"
        :visible.sync="display"
        :before-close="handleClose"
      >
        <mark-batch
          v-if="type === 'mark_batch'"
          @click="handleClose"
          :ips="ips"
        ></mark-batch>
      </el-dialog>
      <ky-table
        :getData="getLogSub"
        :showSelect="showSelect"
        :search_data="search_data"
        :search_criteria="search_criteria"
        :watchs="watchs"
        ref="table"
      >
        <template v-slot:table-action>
          <authorization-button
            class="kylin-item-button"
            @click="handleDownload"
            :disabled="$refs.table && $refs.table.selectRow.ids.length == 0"
            >{{ $t("system.export_select") }}</authorization-button
          >
          <authorization-button
            class="kylin-item-button"
            @click="handleMarkBatch"
            v-if="displaySystem"
            :disabled="$refs.table && $refs.table.selectRow.ids.length == 0"
            >{{ $t("system.mark_batch") }}</authorization-button
          >
          <authorization-button
            class="kylin-item-button"
            @click="reapirLog"
            name="Rpm:repair"
            v-if="detailMessage.module == '补丁模块'"
            :disabled="$refs.table && $refs.table.selectRow.ids.length == 0"
            >{{ $t("patch.repair_package") }}</authorization-button
          >
          <authorization-button
            class="kylin-item-button"
            @click="handleRollback"
            name="log:rollback"
            v-if="
              detailMessage.module == '配置模块' ||
              detailMessage.module == '迁移工具'
            "
            :disabled="$refs.table && $refs.table.selectRow.ids.length == 0"
            >{{ $t("log.configure_rollback") }}</authorization-button
          >
          <authorization-button
            class="kylin-item-button"
            @click="handleRollback('软件包安装')"
            v-if="detailMessage.action == '软件包升级'"
            :disabled="$refs.table && $refs.table.selectRow.ids.length == 0"
            >{{ $t("log.patch_rollback") }}</authorization-button
          >
        </template>
        <template v-slot:table>
          <el-table-column
            v-if="displaySystem"
            :label="$t('system.ip_address')"
            prop="ip"
            width="120"
          >
          </el-table-column>
          <el-table-column :label="$t('log.execution_action')" prop="action">
          </el-table-column>
          <el-table-column
            prop="system"
            v-if="displaySystem"
            :label="$t('system.operating_system')"
            width="210"
          >
          </el-table-column>
          <el-table-column
            prop="version"
            :label="$t('system.version')"
            v-if="displaySystem"
          >
          </el-table-column>
          <el-table-column
            prop="arch"
            :label="$t('system.architecture')"
            v-if="displaySystem"
          >
          </el-table-column>
          <el-table-column
            v-if="
              detailMessage.module == '配置模块' ||
              detailMessage.module == '迁移工具' ||
              detailMessage.action == '软件包升级'
            "
            :label="$t('log.can_rollback')"
          >
            <template slot-scope="scope">
              {{ String(scope.row.canRollback) }}
            </template>
          </el-table-column>
          <el-table-column
            v-if="detailMessage.module == '补丁模块'"
            :label="$t('log.can_repair')"
          >
            <template slot-scope="scope">
              {{ String(scope.row.canRepair) }}
            </template>
          </el-table-column>
          <el-table-column prop="createdAt" :label="$t('log.occurrence_time')">
          </el-table-column>
          <el-table-column prop="status" :label="$t('system.status')">
          </el-table-column>
          <el-table-column
            prop="detailShort"
            :label="$t('log.information_code')"
          >
          </el-table-column>
          <el-table-column
            prop="scriptRet"
            v-if="detailMessage.module == '自定义脚本模块'"
            :label="$t('log.script_ret')"
          >
          </el-table-column>
          <el-table-column>
            <template slot="header">
              {{ $t("log.log_detail") }}
            </template>
            <template slot-scope="scope">
              <el-button
                @click.native.prevent="handleDrawer(scope.row)"
                type="text"
                size="medium"
              >
                {{ $t("log.view_detail") }}
              </el-button>
            </template>
          </el-table-column>
        </template>
      </ky-table>
    </template>
  </page>
</template>

<script>
import Page from "@/components/Page";
import kyTable from "@/components/KyTable";
import {
  getLogSub,
  getLogDetail,
  exportSubLog,
  logRollback,
  logBackOff,
} from "@/api/log";
import { repairpackages } from "@/api/patch";
import Search from "@/components/Search";
import { download } from "@/utils";
import AuthorizationButton from "@/components/AuthorizationButton";
import MarkBatch from "../../system/form/markBatch.vue";
export default {
  components: {
    Page,
    kyTable,
    Search,
    AuthorizationButton,
    MarkBatch,
  },
  data() {
    return {
      search_criteria: {
        id: this.$route.params.id,
        sortBy: "id",
        sortOrder: "desc",
        /* code: "", */
        ip: "",
        version: "",
      },
      display: false,
      title: "",
      timer: null,
      detailTimer: null,
      detailMessage: {},
      drawer: false,
      type: "",
      detail: "",
      ips: [],
      versions: ["V7.0", "V10(SP1)", "V10(SP2)"],
      /* codes: [], */
      showSelect: true,
      search_data: {
        action: {
          name: "log.execution_action",
          type: "text",
        },
        osInfo: {
          name: "system.operating_system",
          type: "select",
          items: [
            {
              key: "中标麒麟高级服务器操作系统V7.0",
              name: "中标麒麟高级服务器操作系统V7.0",
            },
            {
              key: "银河麒麟高级服务器操作系统V10(SP1)",
              name: "银河麒麟高级服务器操作系统V10(SP1)",
            },
            {
              key: "银河麒麟高级服务器操作系统V10(SP2)",
              name: "银河麒麟高级服务器操作系统V10(SP2)",
            },
          ],
        },
        architecture: {
          name: "system.architecture",
          type: "select",
          items: [
            {
              key: "aarch64",
              name: "aarch64",
            },
            {
              key: "x86_64",
              name: "x86_64",
            },
          ],
        },
        createdAt: {
          name: "log.occurrence_time",
          type: "date",
        },
        status: {
          name: "system.status",
          type: "select",
          items: [
            {
              key: "等待执行",
              name: "等待执行",
            },
            {
              key: "运行中",
              name: "运行中",
            },
            {
              key: "取消",
              name: "取消",
            },
            {
              key: "暂停",
              name: "暂停",
            },
            {
              key: "成功",
              name: "成功",
            },
            {
              key: "失败",
              name: "失败",
            },
          ],
        },
        canRollback: {
          name: "log.can_rollback",
          type: "select",
          items: [
            { key: true, name: "true" },
            { key: false, name: "false" },
          ],
        },
        canRepair: {
          name: "log.can_repair",
          type: "select",
          items: [
            { key: true, name: "true" },
            { key: false, name: "false" },
          ],
        },
        detailShort: {
          name: "log.information_code",
          type: "text",
        },
        scriptRet: {
          name: "log.script_ret",
          type: "text",
        },
      },
      watchs: {
        tableData: function (newData) {
          let _this = this;
          let running = false;
          for (let i = 0; i < newData.length; i++) {
            if (
              newData[i].status === "运行中" ||
              newData[i].status === "等待执行"
            ) {
              running = true;
              break;
            }
          }
          if (running) {
            this.timer = this.timer
              ? this.timer
              : setInterval(() => {
                  this.refresh();
                }, 1000);
          } else {
            this.timer && clearInterval(this.timer);
            this.timer = null;
          }
        },
      },
    };
  },
  computed: {
    getColor() {
      if (this.detailMessage.status === "成功") {
        return "#67C23A";
      } else if (this.detailMessage.status === "失败") {
        return "red";
      } else {
        return "";
      }
    },
    getProgress() {
      if (this.detailMessage.progress) {
        let [done, sum] = this.detailMessage.progress.split("/");
        return (done / sum) * 100;
      } else {
        return 0;
      }
    },
    displaySystem() {
      let action = this.detailMessage.action;
      let actions = ["RPM解析", "SP升级解析", "解析XML", "软件包组同步"];
      return !actions.includes(action);
    },
  },
  beforeDestroy() {
    this.timer && clearInterval(this.timer);
    this.detailTimer && clearInterval(this.detailTimer);
  },
  async mounted() {
    const res = await getLogDetail({ id: this.$route.params.id });
    this.detailMessage = res.data && res.data.data;
    if (
      this.detailMessage.module != "配置模块" &&
      this.detailMessage.module != "迁移工具" &&
      this.detailMessage.action != "软件包升级"
    ) {
      delete this.search_data["canRollback"];
    }
    if (
      this.detailMessage.action != "软件包安装" &&
      this.detailMessage.action != "软件包升级"
    ) {
      delete this.search_data["canRepair"];
    }
    if (!this.displaySystem) {
      delete this.search_data["system"];
      delete this.search_data["architecture"];
    }
    if (this.detailMessage.module != "自定义脚本模块") {
      delete this.search_data["scriptRet"];
    }
  },
  methods: {
    getLogSub,
    format(row) {
      return (per) => {
        return this.detailMessage.progress;
      };
    },
    handleDrawer(row) {
      this.detail = row.detail;
      this.drawer = true;
    },
    async handleDownload() {
      let ids;
      if (this.$refs.table.select_id == "2") {
        let data = await this.getAllLog();
        ids = data.ids;
      } else {
        ids = this.$refs.table.selectRow.ids;
      }
      exportSubLog({ subLogIds: ids }).then((res) => {
        download(res, "log");
      });
    },
    handleReset() {
      this.search_criteria.code = "";
      this.search_criteria.version = "";
      this.search_criteria.ip = "";
      this.$refs.table.handleSearch();
    },
    async getAllLog() {
      let canRollback = true,
        canRepair = true,
        ids = [];
      let res = await getLogSub({
        ...this.$route.query,
        ...this.search_criteria,
        paged: false,
      });
      let data = res.data.data.results;
      data.forEach((item) => {
        if (!this.$refs.table.selectRow.excludeIds.includes(item.id)) {
          if (!item.canRollback) {
            canRollback = false;
          }
          if (!item.canRepair) {
            canRepair = false;
          }
          ids.push(item.id);
        }
      });
      return { canRollback, ids, canRepair };
    },
    async reapirLog() {
      let canRepair = true,
        ids;
      if (this.$refs.table.select_id == "2") {
        let data = await this.getAllLog();
        ids = data.ids;
        canRepair = data.canRepair;
      } else {
        ids = this.$refs.table.selectRow.ids;
        this.$refs.table.selectRow.rows.forEach((row) => {
          if (!row.canRepair) {
            canRepair = false;
          }
        });
      }
      if (canRepair) {
        repairpackages(ids).then((res) => {
          if (res.data.code == "0") {
            this.$message({
              type: "success",
              message: res.data.message,
            });
            this.$emit("click", "success");
            this.$router.push({
              name: "log_detail",
              params: { id: res.data.data.id },
            });
          } else {
            this.$message({
              type: "error",
              message: res.data.message,
            });
          }
        });
      } else {
        this.$message({
          type: "error",
          message: this.$t("log.repair_error_message"),
        });
      }
    },
    async handleRollback(type) {
      let canRollback = true,
        ids;
      if (this.$refs.table.select_id == "2") {
        let data = await this.getAllLog();
        ids = data.ids;
        canRollback = data.canRollback;
      } else {
        ids = this.$refs.table.selectRow.ids;
        this.$refs.table.selectRow.rows.forEach((row) => {
          if (!row.canRollback) {
            canRollback = false;
          }
        });
      }
      if (canRollback) {
        if (type === "软件包安装") {
          logBackOff(ids).then((res) => {
            if (res.data.code == "0") {
              this.$message({
                type: "success",
                message: res.data.message,
              });
              this.$emit("click", "success");
              this.$router.push({
                name: "log_detail",
                params: { id: res.data.data.parentId },
              });
            } else {
              this.$message({
                type: "error",
                message: res.data.message,
              });
            }
          });
        } else {
          logRollback({ parentLogId: this.$route.params.id, logIds: ids }).then(
            (res) => {
              if (res.data.code == "0") {
                this.$message({
                  type: "success",
                  message: res.data.message,
                });
                this.$emit("click", "success");
                this.$router.push({
                  name: "log_detail",
                  params: { id: res.data.data.parentId },
                });
              } else {
                this.$message({
                  type: "error",
                  message: res.data.message,
                });
              }
            }
          );
        }
      } else {
        this.$message({
          type: "error",
          message: this.$t("log.rollback_error_message"),
        });
      }
    },
    handleClose() {
      this.display = false;
      this.title = "";
      this.type = "";
    },
    handleSearch() {
      this.$refs.table.handleSearch();
    },
    async getSelectAllIPs() {
      let ips = [];
      let res = await getLogSub({
        ...this.$route.query,
        ...this.search_criteria,
        paged: false,
      });
      res.data.data.results.forEach((item) => {
        ips.push(item.ip);
      });
      return ips;
    },
    async handleMarkBatch() {
      this.display = true;
      let ips = [];
      this.title = this.$t("system.mark_batch");
      this.type = "mark_batch";
      if (this.$refs.table.select_id == "2") {
        this.ips = await this.getSelectAllIPs();
      } else {
        this.$refs.table.selectRow.rows.forEach((item) => {
          ips.push(item.ip);
        });
        this.ips = ips;
      }
    },
  },
  watch: {
    detailMessage: function (value) {
      if (value.status === "运行中") {
        this.detailTimer = this.detailTimer
          ? this.detailTimer
          : setInterval(() => {
              getLogDetail({ id: this.$route.params.id }).then((res) => {
                this.detailMessage = res.data && res.data.data;
              });
            }, 1000);
      } else {
        if (this.detailTimer) {
          clearInterval(this.detailTimer);
          this.detailTimer = null;
        }
      }
    },
    $route: async function (value) {
      const res = await getLogDetail({ id: this.$route.params.id });
      this.detailMessage = res.data && res.data.data;
      if (
        this.detailMessage.module != "配置模块" &&
        this.detailMessage.module != "迁移工具"
      ) {
        delete this.search_data["canRollback"];
      }
      this.$refs.table.refresh();
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.search {
  margin-top: 20px;
}
.label {
  font-weight: 600;
  margin-right: 10px;
}
.drawer {
  white-space: pre-line;
}
.progress {
  width: 30%;
}
.script_content {
  width: 30%;
  height: 100px;
  overflow: auto;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 5px;
  white-space: pre-line;
}
</style>